package com.dwxt.community.service;

import com.alibaba.fastjson.*;
import com.dwxt.common.base.*;
import com.dwxt.common.util.*;
import com.dwxt.community.admin.service.BroadcastHotService;
import com.dwxt.community.dao.*;
import com.dwxt.community.entity.*;
import com.dwxt.community.entity.dto.*;
import com.dwxt.community.entity.enumerate.*;
import com.dwxt.community.entity.vo.*;
import com.github.pagehelper.*;
import org.apache.commons.lang3.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;
import org.springframework.transaction.annotation.*;

import java.util.*;
import java.util.stream.*;

/**
 * 直播 服务层
 *
 * @author
 */
@Service
public class BroadcastService {

    @Autowired
    private BroadcastMapper broadcastMapper;
    @Autowired
    private BroadcastHotService broadcastHotService;
    @Autowired
    private BroadcastColumnMapper broadcastColumnMapper;
    @Autowired
    private ColumnTypeMapper columnTypeMapper;
    @Autowired
    private UserActionRecordService userActionRecordService;

    /**
     * 查询所有栏目  并且栏目下包含的多个直播   深
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    public BaseResult getIncludeChild(Integer pageNum, Integer pageSize, String type) {
        //PageHelper.startPage(pageNum, pageSize);
        //PageInfo pageInfo = new PageInfo(broadcastMapper.selectIncludeChild(type));
        return BaseResult.ok(broadcastMapper.selectIncludeChild(type));
    }

    /**
     * 修改
     *
     * @param broadcastColumns
     * @return
     */
    public BaseResult update(BroadcastColumnDto broadcastColumns) {
        List<Broadcast> broadcasts = broadcastColumns.getBroadcasts();
        List<Broadcast> sqlBroadcasts = broadcastMapper.selectByColumnId(broadcastColumns.getId());
        //批量修改栏目下的直播
        for (Broadcast broadcast : broadcasts) {
            //新增
            if (StringUtils.isBlank(broadcast.getId())) {
                Date date = new Date();
                broadcast.setId(IDUtils.genItemId());
                broadcast.setColumeId(broadcastColumns.getId());
                broadcast.setCreateTime(date);
                broadcast.setUpdateTime(date);
                broadcastMapper.insertSelective(broadcast);
            } else {
            //修改
                broadcastMapper.updateByPrimaryKeySelective(broadcast);
            }
        }
            //删除
        for (Broadcast sqlBroadcast : sqlBroadcasts) {
            if (!broadcasts.stream().map(Broadcast::getId).collect(Collectors.toList()).contains(sqlBroadcast.getId())) {
                broadcastMapper.deleteByPrimaryKey(sqlBroadcast.getId());
            }
        }
        //修改栏目
        int i = broadcastColumnMapper.updateByPrimaryKeySelective(broadcastColumns);
        return BaseResult.build(i > 0 ? StatusCode.SUCCESS : StatusCode.FAIL, i);
    }

    /**
     * 直播列表 or 搜索
     *
     * @param pageNum
     * @param pageSize
     * @param type
     * @param name
     * @return
     */
    public BaseResult get(Integer pageNum, Integer pageSize, String type, String name) {
        PageHelper.startPage(pageNum, pageSize);
        PageInfo pageInfo = new PageInfo(broadcastMapper.selectAll(type, name));
        return BaseResult.ok(pageInfo);
    }

    public BaseResult getDesk(Integer pageNum, Integer pageSize, String type, String name) {
        PageHelper.startPage(pageNum, pageSize);
        PageInfo pageInfo = new PageInfo(broadcastMapper.selectDesk(type, name));
        return BaseResult.ok(pageInfo);
    }

    /**
     * 添加栏目
     *
     * @param broadcastColumns
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public BaseResult insert(BroadcastColumnDto broadcastColumns) {

        Date date = new Date();

        //设置栏目ID
        String columnId = IDUtils.genItemId();
        broadcastColumns.setId(columnId);

        //设置时间
        broadcastColumns.setCreateTime(date);
        broadcastColumns.setUpdateTime(date);

        //插入栏目
        int i = broadcastColumnMapper.insertSelective(broadcastColumns);

        //处理栏目下的直播
        List<Broadcast> broadcasts = broadcastColumns.getBroadcasts();
        if (broadcasts != null) {
            for (Broadcast broadcast : broadcasts) {
                broadcast.setCreateTime(date);
                broadcast.setUpdateTime(date);
                broadcast.setId(IDUtils.genItemId());
                //绑定栏目ID
                broadcast.setColumeId(columnId);
            }
            //插入直播
            i += broadcastMapper.insertBatch(broadcasts);
        }
        return BaseResult.build(i > 0 ? StatusCode.SUCCESS : StatusCode.FAIL, i);
    }

    /**
     * 删除栏目
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public BaseResult del(String id) {
        //删除热门视频表中数据
        List<Broadcast> broadcasts = broadcastMapper.selectByColumnId(id);
        for (Broadcast b : broadcasts) {
            broadcastHotService.delByBroadcastId(b.getId());
        }
        //删除栏目下的所有直播
        broadcastMapper.deleteByColumnId(id);
        //删除栏目
        broadcastColumnMapper.deleteByPrimaryKey(id);
        return BaseResult.ok();
    }

    /**
     * 删除栏目下的某直播
     *
     * @param id
     * @return
     */
    public BaseResult delBroadcast(String id) {
        broadcastMapper.deleteByPrimaryKey(id);
        broadcastHotService.delByBroadcastId(id);
        return BaseResult.ok();
    }

    /**
     * 栏目类型
     *
     * @return
     */
    public BaseResult getColumeType() {
        return BaseResult.ok(columnTypeMapper.selectByExample(null));
    }

    /**
     * 停用  or  启用
     *
     * @return
     */
    public BaseResult useOrStop(String id) {

        BroadcastColumn broadcastColumn = broadcastColumnMapper.selectByPrimaryKey(id);

        if (broadcastColumn == null) {
            return BaseResult.build(StatusCode.PARAMETER_WRONG);
        }

        if (StateConstant.USE.getCode().equals(broadcastColumn.getUse())) {
            broadcastColumn.setUse(StateConstant.STOP.getCode());
            //撤下热门视频
            List<Broadcast> broadcasts = broadcastMapper.selectByColumnId(id);
            if (ObjectUtils.isNotEmpty(broadcasts)){
                for (Broadcast b:broadcasts) {
                    broadcastHotService.delByBroadcastId(b.getId());
                }
            }

        } else if (StateConstant.STOP.getCode().equals(broadcastColumn.getUse())) {
            broadcastColumn.setUse(StateConstant.USE.getCode());
        }

        int i = broadcastColumnMapper.updateByPrimaryKey(broadcastColumn);

        return BaseResult.build(i > 0 ? StatusCode.SUCCESS : StatusCode.FAIL);
    }

    /**
     * 获取热门视频
     * @param pageNum
     * @param pageSize
     * @param type
     * @return
     */
    public BaseResult getHot() {
        return BaseResult.ok(broadcastColumnMapper.selectHot());
    }

    public BaseResult broadcastByColumnId(Integer pageNum, Integer pageSize, String id) {
        BroadcastColumn broadcastColumn = broadcastColumnMapper.selectByPrimaryKey(id);
        if (broadcastColumn==null || broadcastColumn.getUse() == YesOrNo.NO ){
            return BaseResult.build(StatusCode.COLUMN_NOT_EXIST);
        }
        PageHelper.startPage(pageNum,pageSize);
        List<Broadcast> broadcasts = broadcastMapper.selectByColumnId(id);
        return BaseResult.ok(new PageInfo<>(broadcasts));
    }

    /**
     * 栏目详情
     * @param id
     * @return
     */
    public BaseResult detail(String id) {
        BroadcastColumnVo broadcastColumnVo = broadcastMapper.selectById(id);
        return BaseResult.ok(broadcastColumnVo);

    }

    /**
     * 通过直播ID获取直播详情并且包含相关视频
     * @param id
     * @return
     */
    public BaseResult broadcastDetailAndCorrelation(String id) {
        //添加行为记录
        String currentUserId = PartyUtil.getCurrentUserId();
        userActionRecordService.addActionRecord(id, StringUtils.isNotBlank(currentUserId)?currentUserId:"游客","直播",ActionInfoEnum.hit.getCode());

        Broadcast broadcast = broadcastMapper.selectIncludeColumnDescByPrimaryKey(id);
        if (broadcast == null){
            return BaseResult.build(StatusCode.VIDEO_NOT_EXIST);
        }
        List<Broadcast> rejectBroadcast = broadcastMapper.selectByRejectPrimaryKey(broadcast.getColumeId(),id);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("broadcast",broadcast);
        jsonObject.put("correlation",rejectBroadcast);
        return BaseResult.ok(jsonObject);
    }

    public BaseResult getHotVideo() {
        return BaseResult.ok(broadcastMapper.selectHotVideo());
    }
}
